library(tidyverse) # for data cleaning and plotting
## ── Attaching packages ─────────────────────────────────────── tidyverse 1.3.0 ──
## ✓ ggplot2 3.3.3 ✓ purrr 0.3.4
## ✓ tibble 3.0.6 ✓ dplyr 1.0.2
## ✓ tidyr 1.1.2 ✓ stringr 1.4.0
## ✓ readr 1.4.0 ✓ forcats 0.5.0
## ── Conflicts ────────────────────────────────────────── tidyverse_conflicts() ──
## x dplyr::filter() masks stats::filter()
## x dplyr::lag() masks stats::lag()
library(gardenR) # for Lisa's garden data
library(lubridate) # for date manipulation
##
## Attaching package: 'lubridate'
## The following objects are masked from 'package:base':
##
## date, intersect, setdiff, union
library(openintro) # for the abbr2state() function
## Loading required package: airports
## Loading required package: cherryblossom
## Loading required package: usdata
library(palmerpenguins)# for Palmer penguin data
library(maps) # for map data
##
## Attaching package: 'maps'
## The following object is masked from 'package:purrr':
##
## map
library(ggmap) # for mapping points on maps
## Google's Terms of Service: https://cloud.google.com/maps-platform/terms/.
## Please cite ggmap if you use it! See citation("ggmap") for details.
library(gplots) # for col2hex() function
##
## Attaching package: 'gplots'
## The following object is masked from 'package:stats':
##
## lowess
library(RColorBrewer) # for color palettes
library(sf) # for working with spatial data
## Linking to GEOS 3.8.1, GDAL 3.1.4, PROJ 6.3.1
library(leaflet) # for highly customizable mapping
library(ggthemes) # for more themes (including theme_map())
library(plotly) # for the ggplotly() - basic interactivity
##
## Attaching package: 'plotly'
## The following object is masked from 'package:ggmap':
##
## wind
## The following object is masked from 'package:ggplot2':
##
## last_plot
## The following object is masked from 'package:stats':
##
## filter
## The following object is masked from 'package:graphics':
##
## layout
library(gganimate) # for adding animation layers to ggplots
library(transformr) # for "tweening" (gganimate)
##
## Attaching package: 'transformr'
## The following object is masked from 'package:sf':
##
## st_normalize
library(gifski) # need the library for creating gifs but don't need to load each time
library(shiny) # for creating interactive apps
library(wesanderson) # plot colors
library(lemon) # garden graph plot
##
## Attaching package: 'lemon'
## The following object is masked from 'package:purrr':
##
## %||%
## The following objects are masked from 'package:ggplot2':
##
## CoordCartesian, element_render
library(ggtext) # garden graph plot
theme_set(theme_minimal())
# SNCF Train data
small_trains <- read_csv("https://raw.githubusercontent.com/rfordatascience/tidytuesday/master/data/2019/2019-02-26/small_trains.csv")
##
## ── Column specification ────────────────────────────────────────────────────────
## cols(
## year = col_double(),
## month = col_double(),
## service = col_character(),
## departure_station = col_character(),
## arrival_station = col_character(),
## journey_time_avg = col_double(),
## total_num_trips = col_double(),
## avg_delay_all_departing = col_double(),
## avg_delay_all_arriving = col_double(),
## num_late_at_departure = col_double(),
## num_arriving_late = col_double(),
## delay_cause = col_character(),
## delayed_number = col_double()
## )
# Lisa's garden data
data("garden_harvest")
# Lisa's Mallorca cycling data
mallorca_bike_day7 <- read_csv("https://www.dropbox.com/s/zc6jan4ltmjtvy0/mallorca_bike_day7.csv?dl=1") %>%
select(1:4, speed)
##
## ── Column specification ────────────────────────────────────────────────────────
## cols(
## lon = col_double(),
## lat = col_double(),
## ele = col_double(),
## time = col_datetime(format = ""),
## extensions = col_double(),
## ele.num = col_double(),
## date = col_date(format = ""),
## hrminsec = col_datetime(format = ""),
## time_hr = col_double(),
## dist_km = col_double(),
## speed = col_double()
## )
# Heather Lendway's Ironman 70.3 Pan Am championships Panama data
panama_swim <- read_csv("https://raw.githubusercontent.com/llendway/gps-data/master/data/panama_swim_20160131.csv")
##
## ── Column specification ────────────────────────────────────────────────────────
## cols(
## lon = col_double(),
## lat = col_double(),
## time = col_datetime(format = ""),
## extensions = col_double(),
## ele = col_logical(),
## event = col_character(),
## date = col_date(format = ""),
## hrminsec = col_datetime(format = "")
## )
panama_bike <- read_csv("https://raw.githubusercontent.com/llendway/gps-data/master/data/panama_bike_20160131.csv")
##
## ── Column specification ────────────────────────────────────────────────────────
## cols(
## lon = col_double(),
## lat = col_double(),
## ele = col_double(),
## time = col_datetime(format = ""),
## extensions = col_double(),
## event = col_character(),
## date = col_date(format = ""),
## hrminsec = col_datetime(format = "")
## )
panama_run <- read_csv("https://raw.githubusercontent.com/llendway/gps-data/master/data/panama_run_20160131.csv")
##
## ── Column specification ────────────────────────────────────────────────────────
## cols(
## lon = col_double(),
## lat = col_double(),
## ele = col_double(),
## time = col_datetime(format = ""),
## extensions = col_double(),
## event = col_character(),
## date = col_date(format = ""),
## hrminsec = col_datetime(format = "")
## )
#COVID-19 data from the New York Times
covid19 <- read_csv("https://raw.githubusercontent.com/nytimes/covid-19-data/master/us-states.csv")
##
## ── Column specification ────────────────────────────────────────────────────────
## cols(
## date = col_date(format = ""),
## state = col_character(),
## fips = col_character(),
## cases = col_double(),
## deaths = col_double()
## )
Go here or to previous homework to remind yourself how to get set up.
Once your repository is created, you should always open your project rather than just opening an .Rmd file. You can do that by either clicking on the .Rproj file in your repository folder on your computer. Or, by going to the upper right hand corner in R Studio and clicking the arrow next to where it says Project: (None). You should see your project come up in that list if you’ve used it recently. You could also go to File –> Open Project and navigate to your .Rproj file.
Put your name at the top of the document.
For ALL graphs, you should include appropriate labels.
Feel free to change the default theme, which I currently have set to theme_minimal().
Use good coding practice. Read the short sections on good code with pipes and ggplot2. This is part of your grade!
NEW!! With animated graphs, add eval=FALSE to the code chunk that creates the animation and saves it using anim_save(). Add another code chunk to reread the gif back into the file. See the tutorial for help.
When you are finished with ALL the exercises, uncomment the options at the top so your document looks nicer. Don’t do it before then, or else you might miss some important warnings and messages.
ggplotly() function.income_distribution <- readr::read_csv('https://raw.githubusercontent.com/rfordatascience/tidytuesday/master/data/2021/2021-02-09/income_distribution.csv')
##
## ── Column specification ────────────────────────────────────────────────────────
## cols(
## year = col_double(),
## race = col_character(),
## number = col_double(),
## income_median = col_double(),
## income_med_moe = col_double(),
## income_mean = col_double(),
## income_mean_moe = col_double(),
## income_bracket = col_character(),
## income_distribution = col_double()
## )
tidy_tues <- income_distribution %>%
filter(year >= 2002,
!race %in% c("Asian Alone", "Black Alone", "White Alone")) %>%
mutate(Race = ifelse(race == "Asian Alone or in Combination", "Asian",
ifelse(race == "Black Alone or in Combination", "Black",
ifelse(race == "White Alone, Not Hispanic", "White", race))),
median_income_thou = income_median/1000) %>%
ggplot(aes(x = year, y = median_income_thou, color = Race)) +
labs(x = "", y = "", title = "Median income (in thousands of dollars) from 2002 to 2019 by race", color = "", caption = "Created by: Nolan Meyer") +
geom_line(size = 1) +
geom_text(aes(x = 2019, y = 99, label = "Asian", color = "Asian"), size = 4) +
geom_text(aes(x = 2019, y = 78, label = "White", color = "White"), size = 4) +
geom_text(aes(x = 2018.9, y = 70, label = "All Races", color = "All Races"), size = 4) +
geom_text(aes(x = 2017.8, y = 58, label = "Hispanic (Any Race)", color = "Hispanic (Any Race)"), size = 4) +
geom_text(aes(x = 2019, y = 48, label = "Black", color = "Black"), size = 4) +
ylim(35, 100) +
scale_color_manual(values=wes_palette(n = 5, name = "Darjeeling2")) +
theme(plot.title = element_text(size = 11, face = "bold", hjust = -.5),
panel.grid.major.x = element_blank(),
panel.grid.minor.x = element_blank(),
panel.grid.major.y = element_blank(),
panel.grid.minor.y = element_blank(),
plot.background = element_rect(fill = "ivory"),
legend.position = "none"
)
ggplotly(tidy_tues)
perf_gard <- garden_harvest %>%
group_by(vegetable) %>%
summarize(n = n(),
tot_veg_weight = sum(weight)) %>%
mutate(weight_prop = tot_veg_weight/sum(tot_veg_weight),
quant_prop = n/sum(n),
vegetable = str_to_title(vegetable)) %>%
select(vegetable,
weight_prop,
quant_prop) %>%
slice_max(quant_prop, n = 8) %>%
pivot_longer(cols = weight_prop:quant_prop,
names_to = "proportion",
values_to = "value") %>%
ggplot(aes(x = ifelse(proportion == "quant_prop", yes = -value, no = value),
y = fct_reorder2(vegetable, proportion == "quant_prop", value, .desc = F),
fill = proportion)) +
geom_col(aes(text = value)) +
labs(x = "", y = "",
title = "Proportion of cumulative harvest quantity and cumulative harvest weight by vegetable",
subtitle = "Vegetables in the upper 25th quartile by harvest quantity") +
scale_fill_manual(name = "Proportion", labels = c("Quantity", "Weight"), values = c("purple", "deepskyblue1")) +
scale_x_symmetric(labels = abs) +
theme(axis.line = element_line(colour = "black"),
panel.grid.major.y = element_blank(),
panel.grid.minor.y = element_blank(),
panel.grid.major.x = element_blank(),
panel.grid.minor.x = element_blank(),
axis.text.x = element_text(size = 10, colour = "black"),
axis.text.y = element_text(size = 10, colour = "black"),
panel.border = element_blank(),
panel.background = element_blank(),
legend.position = "none",
plot.title = element_markdown(face = "bold", size = 10.5, hjust = 1),
plot.subtitle = element_text(size = 9, margin = margin(0,0,18,0), hjust = -0.355),
plot.background = element_rect(fill = "snow1"))
## `summarise()` ungrouping output (override with `.groups` argument)
## Warning: Ignoring unknown aesthetics: text
ggplotly(perf_gard,
tooltip = c("value", "x"))
small_trains dataset that contains data from the SNCF (National Society of French Railways). These are Tidy Tuesday data! Read more about it here.small_trains %>%
filter(service == "National", year %in% c(2017)) %>%
group_by(departure_station, month) %>%
summarize(tot_month_trips = sum(total_num_trips)) %>%
mutate(tot_trips = sum(tot_month_trips)) %>%
arrange(desc(tot_trips)) %>%
filter(tot_trips > 90000) %>% # top 5 stations by number of trips
ggplot(aes(x = month, y = tot_month_trips, color = departure_station)) +
geom_line() +
labs(x = "",
y = "",
title = "Total number of trips per month in 2017 by departure station",
subtitle = "Station: {closest_state}",
caption = "Top 5 stations by total number of trips in 2017",
color = "") +
scale_x_continuous(breaks = seq(1, 12, 1)) +
theme(legend.position = "none") +
transition_states(departure_station,
transition_length = 1,
state_length = 2)
anim_save("stationplot.gif")
geom_area() examples here). You will look at cumulative harvest of tomato varieties over time. You should do the following:garden_harvest data, filter the data to the tomatoes and find the daily harvest in pounds for each variety.fct_reorder()) from most to least harvested (most on the bottom).I have started the code for you below. The complete() function creates a row for all unique date/variety combinations. If a variety is not harvested on one of the harvest dates in the dataset, it is filled with a value of 0.
garden_harvest %>%
filter(vegetable == "tomatoes") %>%
group_by(date, variety) %>%
summarize(daily_harvest_lb = sum(weight)*0.00220462) %>%
ungroup() %>%
complete(variety, date, fill = list(daily_harvest_lb = 0)) %>%
group_by(variety) %>%
mutate(cum_harvest_lb = cumsum(daily_harvest_lb)) %>%
ggplot() +
geom_area(aes(x = date, y = cum_harvest_lb, fill = fct_reorder2(variety, variety, cum_harvest_lb, .desc = FALSE))) +
theme(legend.position = "top") +
labs(x = "",
y = "",
title = "Cumulative harvest over time of tomatoes (lbs) by variety",
subtitle = "Date: {frame_along}",
fill = "") +
transition_reveal(date)
anim_save("cum_harvest.gif")
mallorca_bike_day7 bike ride using animation! Requirements:ggmap.ggimage package and geom_image to add a bike image instead of a red point. You can use this image. See here for an example.mallorca_map <- get_stamenmap(
bbox = c(left = 2.28, bottom = 39.55, right = 2.6, top = 39.7),
maptype = "terrain",
zoom = 12)
map_anim <- ggmap(mallorca_map) +
geom_path(data = mallorca_bike_day7,
aes(x = lon, y = lat, color = ele),
size = 1) +
geom_point(data = mallorca_bike_day7,
aes(x = lon, y = lat), color = "red",
size = 4) +
scale_color_viridis_c(option = "magma") +
theme_map() +
theme(legend.background = element_blank()) +
labs(title = "Mallorca Bike Ride",
subtitle = "Time: {frame_along}",
color = "Elevation") +
transition_reveal(time)
animate(map_anim, duration = 15)
anim_save("bike_map.gif")